package org.example.ctsbocc.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.example.ctsbocc.entity.User;
import org.example.ctsbocc.service.UserService;
import org.example.ctsbocc.utils.JwtUtil;
import org.example.ctsbocc.utils.LoggerUtil;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;

@RestController
@RequestMapping("/api/loginController")
public class LoginController {

    @Resource(name = "userService")
    private UserService userService;

    @Resource(name = "jwtUtil")
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object> login(@RequestBody Map<String, String> loginRequest,
                      HttpSession session) {

        String gitUsername = loginRequest.get("gitUsername");
        String password = loginRequest.get("password");
        String verificationCode = loginRequest.get("verificationCode");

//        System.out.println(gitUsername + " " + password + " " + verificationCode);

        try {
            String rightCode = (String) session.getAttribute("rightCode");
            if (rightCode == null) {
                LoggerUtil.log().warn("验证码不存在，请先获取验证码");
                return null;
            }

            LoggerUtil.log().info("用户 {} 登录，验证码为 {} ", gitUsername, rightCode);
            User user = userService.selectByGitUsername(gitUsername, password, verificationCode, rightCode);
            LocalDateTime time = LocalDateTime.now();

            if (user != null) {
                session.setAttribute("user", user);
                session.setAttribute("key", time);
                LoggerUtil.log().info("用户 {} 登录成功", gitUsername);
                String token = jwtUtil.generateToken(user, time);
                return Map.of("token", token, "user", user, "key", time);
            }
            return null;
        } catch (Exception e) {
            LoggerUtil.log().error("登录处理异常", e);
            return null;
        }
    }

    @GetMapping("/logout")
    public Boolean logout(HttpSession session) {
        User user = (User) session.getAttribute("user");
        LoggerUtil.log().info("用户{}退出登录", user.getGitUsername());
        session.invalidate();
        return Boolean.TRUE;
    }
}
